package com.gdufe.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gdufe.common.exception.ServiceException;
import com.gdufe.common.feign.ProductFeign;
import com.gdufe.common.utils.PageUtils;
import com.gdufe.common.utils.Query;
import com.gdufe.order.dao.OrderDao;
import com.gdufe.common.entity.OrderEntity;
import com.gdufe.order.service.OrderAdminService;
import com.gdufe.order.vo.AdminOrderDetailsVO;
import com.gdufe.common.entity.Product;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

@Service("orderAdminService")
public class OrderAdminServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderAdminService {

    @Resource(type = ProductFeign.class)
    private ProductFeign productFeign;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        String status = (String) params.get("status");
        QueryWrapper<OrderEntity> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(qw ->
                    qw.eq("id", key).or().eq("user_id", key).or().eq("product_id", key));
        }

        if (!StringUtils.isEmpty(status)) {
            queryWrapper.eq("status", Integer.parseInt(status));
        }
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params), queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public AdminOrderDetailsVO getOrderDetails(Long id){
        //获取数据库订单信息
        OrderEntity order=this.getById(id);
        if(order==null)
            throw new ServiceException(500, "查无此单");
        AdminOrderDetailsVO vo = new AdminOrderDetailsVO();
        BeanUtils.copyProperties(order,vo);
        //获取商品价格和商品名，组成订单详情
        Product product = productFeign.adminSelectById(order.getProductId()).getData(new TypeReference<Product>(){});
        vo.setProductPrice(product.getPrice());
        vo.setProductName(product.getName());
        return vo;
    }
}
